<?php

namespace App\Http\Requests;

use App\Common\Status;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class PositionCategoryRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string|max:30',
            'pid' => 'required|integer',
            'code' => 'nullable|alpha_num',
            'id' => 'nullable|integer',
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => '名称不可空',
            'name.max' => '名称不可大于10个字',
            'pid.required' => '上级id不可空',
            'pid.integer' => '上级id必须整形'
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        $error= $validator->errors()->all();
        throw new HttpResponseException($this->fail(Status::ERROR, $error));
    }

    protected function fail(int $code, array $errors)
    {
        return response()->json(
            [
                'code' => $code,
                'errors' => $errors,
            ]
        );
    }
}

